import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getConfRoutes } from '@/router/conf'
import { cloneDeep } from 'lodash'
const initialState = {
  value: {
    routes: [],
    menus: []
  }
}

function getItem(label, key, icon, children) { // 菜单项处理 [{ key, icon, label, children? }]
  const res = {
    key,
    icon,
    label,
  }
  if (children) res.children = children
  return res
}

const handleMenuItem = (routes, items) => { // menu数据处理
  routes.forEach(item => {
    if (item.path !== '*') { // * 不做匹配
      const icon = item.meta?.icon || null
      if (item.children) {
        // 渲染有权限的路由
        const res = item.children.filter(item => item.meta.hasAuthIn)
        if (res.length) items.push(getItem(item.meta?.title || item.name || '', item?.meta?.key || '', icon, handleMenuItem(item.children, [])))
      } else {
        if (item.meta.hasAuthIn) items.push(getItem(item.meta?.title || item.name || '', item?.meta?.key || '', icon))
      }
    }
  })
  return items
}

const handleRouteItem = (originRoutes, menus, baseURL) => { // 路由数据处理
  return originRoutes.map(item => {
    const path = baseURL + '/' + item.path
    item.meta = {
      ...item.meta,
      key: `/conf${path}`
    }
    if (item.children) {
      return { ...item, children: handleRouteItem(item.children, menus, path)}
    } else {
      // 判断是否有权限进入列表
      const index = menus.findIndex(menu => menu.path === path)
      // notNeedAuth字段表示不需要判断路由权限
      // hasAuthIn用来判断路由是否有权限
      item.meta.hasAuthIn = index > -1 || item.meta.notNeedAuth
      return item
    }
  })
}

export const loadRouteList = createAsyncThunk(
  "routerReducer/loadRouteList",
  (_, { dispatch }) => {
    // mock
    const menus = [
      { id: 4, path: '/car/index', type: 'MENU' },
      { id: 4, path: '/costomer', type: 'MENU' },
      { id: 5, path: '/car/index', type: 'BUTTON' }
      // { id: 2, path: '/user/info/index', type: 'MENU' },
      // { id: 3, path: '/user/index', type: 'MENU' },
    ]
    if (menus) {
      const originRoutes = getConfRoutes()
      // 过滤Menu
      const currentMenus = menus.filter(item => item.type === 'MENU')
      const routeItems = handleRouteItem(cloneDeep(originRoutes), currentMenus, '')
      const menuItems = handleMenuItem(routeItems, [])
      dispatch(changeMenusAction(menuItems))
      dispatch(changeRoutesAction(routeItems))
    }
  }
)


export const routerReducer = createSlice({
  name: 'routerReducer',
  initialState,
  reducers: {
    changeRoutesAction (state, { payload }) {
      state.value.routes = payload
    },
    changeMenusAction (state, { payload }) {
      state.value.menus = payload
    },
    clearRouter (state) {
      state.value = []
    }
  }
})

// Action creators are generated for each case reducer function
export const { clearRouter, changeRoutesAction, changeMenusAction } = routerReducer.actions

export default routerReducer.reducer
